package com.ruoyi.web.sso.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.web.sso.common.util.AssertUtil;
import com.ruoyi.web.sso.common.util.BusinessException;
import com.ruoyi.web.sso.common.util.ErrorCode;
import com.ruoyi.web.sso.common.util.UuidUtil;
import com.ruoyi.web.sso.domain.*;
import com.ruoyi.web.sso.domain.DTO.RoleDTO;
import com.ruoyi.web.sso.domain.DTO.StatusResponse;
import com.ruoyi.web.sso.domain.vo.AddRole;
import com.ruoyi.web.sso.domain.vo.RedisDetails;
import com.ruoyi.web.sso.mapper.*;
import com.ruoyi.web.sso.service.IAreaService;
import com.ruoyi.web.sso.service.IAreaStaffService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.ruoyi.web.sso.service.IRoleService;
import com.ruoyi.common.core.text.Convert;
import org.springframework.transaction.annotation.Transactional;

/**
 * 角色信息Service业务层处理
 * 
 * @author ruoyi
 * @date 2021-10-28
 */
@Service
public class RoleServiceImpl implements IRoleService 
{
    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private PlatformMapper platformMapper;

    @Autowired
    private StaffMapper staffMapper;

    @Autowired
    private GroupMapper groupMapper;

    @Autowired
    private RoleMenuMapper roleMenuMapper;

    @Autowired
    private  StaffRoleMapper staffRoleMapper;

    @Autowired
    private IAreaStaffService areaStaffService;

    @Autowired
    private IAreaService areaService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private AreaStaffMapper areaStaffMapper;

    /**
     * 查询角色信息
     * 
     * @param roleId 角色信息主键
     * @return 角色信息
     */
    @Override
    public Role selectRoleByRoleId(String roleId)
    {
        return roleMapper.selectRoleByRoleId(roleId);
    }


    @Override
    public Role selectRoleByAreaId(String areaId)
    {
        return roleMapper.selectRoleByAreaId(areaId);
    }


    @Override
    public Role selectRoleByRoleIdAndAreaId(String roleId, String areaId) {
        return null;
    }

    /**
     * 查询角色信息列表
     * 
     * @param role 角色信息
     * @return 角色信息
     */
    @Override
    public List<Role> selectRoleList(Role role)
    {
        return roleMapper.selectRoleList(role);
    }

    /**
     * 新增角色信息
     * 
     * @param role 角色信息
     * @return 结果
     */
    @Override
    public int insertRole(Role role)
    {
        role.setCreateTime(DateUtils.getNowDate());
        int i =roleMapper.insertRole(role);
        return i;
    }

    /**
     * 修改角色信息
     * 
     * @param role 角色信息
     * @return 结果
     */
    @Override
    public int updateRole(Role role)
    {
        role.setUpdateTime(DateUtils.getNowDate());
        roleMapper.updateRole(role);

        // 删除角色与菜单关联
        roleMenuMapper.deleteRoleMenuByRoleId(role.getRoleId(),role.getPlatformId());
        AddRole addRole = new AddRole();
        BeanUtils.copyProperties(role , addRole);
        return insertRoleMenu(addRole,role.getRoleId());
    }

    /**
     * 批量删除角色信息
     * 
     * @param roleIds 需要删除的角色信息主键
     * @return 结果
     */
    @Override
    public int deleteRoleByRoleIds(String roleIds)
    {
        return roleMapper.deleteRoleByRoleIds(Convert.toStrArray(roleIds));
    }

    /**
     * 删除角色信息信息
     * 
     * @param roleId 角色信息主键
     * @return 结果
     */
    @Override
    public int deleteRoleByRoleId(String roleId)
    {
        return roleMapper.deleteRoleByRoleId(roleId);
    }


    @Override
    @Transactional
    public AjaxResult add(AddRole addRole) {
        Platform platform  = platformMapper.selectPlatformByPlatformId(addRole.getPlatformId());
        if (AssertUtil.isEmpty(platform)){
            return AjaxResult.error("系统ID不存在！");
        }

        Role sosRole = new Role();
        BeanUtils.copyProperties(addRole , sosRole);
        sosRole.setRoleId(UuidUtil.getUuid());
        Role role2 = roleMapper.getAreaByRoleName(sosRole.getAreaId(),sosRole.getRoleName());
        if (AssertUtil.isNotEmpty(role2)){
            throw new BusinessException(ErrorCode.STAFF_HAS_NO_ROLE, "角色已存在");
        }
        roleMapper.insertRole(sosRole);
        //添加角色菜单
        insertRoleMenu(addRole,sosRole.getRoleId());
        //更新redis角色信息
        //setRedisRoleMenu(sosRole.getRoleId());
        return AjaxResult.success("添加成功！");
    }


    /**
     * 新增角色菜单信息
     *
     */
    public int insertRoleMenu(AddRole role,String id)
    {
        int rows = 1;
        if (StringUtils.equals("",role.getMenuIds())){
            return 1;
        }
        // 新增用户与角色管理
        List<RoleMenu> list = new ArrayList<RoleMenu>();
        String [] yy =dosplit( role.getMenuIds());
        for (String menuId : yy)
        {
            RoleMenu rm = new RoleMenu();
            rm.setRoleId(id);
            rm.setMenuId(menuId);
            list.add(rm);
        }
        if (list.size() > 0)
        {
            rows = roleMenuMapper.batchRoleMenu(list);
        }
        //更新redis角色信息
        //setRedisRoleMenu(id);
        return rows;
    }

    public String[] dosplit(String string) {
        String[] result=string.split(",");
        return result;
    }


    @Override
    public AjaxResult addStaffRole(StaffRole staffRole) throws Exception {
        Staff staff =staffMapper.selectStaffById(staffRole.getStaffId());
        if (AssertUtil.isEmpty(staff)){
           throw new Exception("用户不存在");
        }
        Role role =roleMapper.selectRoleByRoleId(staffRole.getRoleId());
        if (AssertUtil.isEmpty(role)){
            throw new Exception("角色ID不存在");
        }

        StaffRole staffRole1 = new StaffRole();
        staffRole1.setStaffId(staffRole.getStaffId());
        staffRole1.setIsDefault(1);
        List<StaffRole> list =staffRoleMapper.selectStaffRoleList(staffRole1);
        if (list.size()==0){
            staffRole.setIsDefault(1);
        }

        //查询园区默认角色
        AreaStaff areaStaff = areaStaffMapper.getStaffArea(staff.getAreaId(), staffRole.getStaffId());
        if (AssertUtil.isEmpty(areaStaff)) {
            AreaStaff areaStaff1 = new AreaStaff();
            areaStaff1.setAreaId(staff.getAreaId());
            areaStaff1.setStaffId(staffRole.getStaffId());
            areaStaff1.setRoleId(role.getRoleId());
            areaStaffMapper.insertAreaStaff(areaStaff1);
        }else {
            //处理数据异常情况
            Role role1 =roleMapper.selectRoleByRoleId(areaStaff.getRoleId());
            if (AssertUtil.isNotEmpty(role1)){
                if ( !StringUtils.equals(role1.getAreaId(),staff.getAreaId())){
                    areaStaff.setRoleId(role.getRoleId());
                    areaStaffMapper.updateAreaStaff(areaStaff);
                }
            }

        }
        staffRoleMapper.insertStaffRole(staffRole);

        return AjaxResult.success("成功");
    }

    @Override
    public StatusResponse addRole(StaffRole staffRole) {
        Staff staff = staffMapper.selectStaffById(staffRole.getStaffId());
        if (AssertUtil.isEmpty(staff)){
            return  StatusResponse.error(ErrorCode.STAFF_NOT_EXIST,"账号不存在！");
        }
        Role role = roleMapper.selectRoleByRoleId(staffRole.getRoleId());
        if (AssertUtil.isEmpty(role) || !staff.getAreaId().equals(role.getAreaId())){
            return  StatusResponse.error(ErrorCode.STAFF_NOT_EXIST,"角色不存在！");
        }
//        Platform platform  = platformMapper.selectPlatformByPlatformId(staffRole.getPlatformId());
//        if (AssertUtil.isEmpty(platform)){
//            return  StatusResponse.error(ErrorCode.STAFF_NOT_EXIST,"系统id不存在！");
//        }


        StaffRole staffRole1 = new StaffRole();
        staffRole1.setStaffId(staffRole.getStaffId());
//        staffRole1.setPlatformId(staffRole.getPlatformId());
        staffRole1.setIsDefault(1);
        List<StaffRole> list =staffRoleMapper.selectStaffRoleList(staffRole1);
        if (list.size()==0){
            staffRole.setIsDefault(1);
        }

        StaffRole staffRole2 =  staffRoleMapper.selectIsExistence(staffRole);

        if (AssertUtil.isEmpty(staffRole2)){
            staffRoleMapper.insertStaffRole(staffRole);
            return StatusResponse.success( "添加成功");
        }else {
            return  StatusResponse.error(ErrorCode.RECORD_DUPLICATED,"数据已存在！");
        }
    }

    public  void  addRole(String staffId,String roleId){
        if (AssertUtil.isEmpty(roleMapper.selectRoleByRoleId(roleId))){
            throw new BusinessException(ErrorCode.ROLE_NOT_EXIST, "用户没有改角色");
        }
        StaffRole staffRole = new StaffRole();
        staffRole.setStaffId(staffId);
        staffRole.setRoleId(roleId);
        StaffRole staffRole2 =staffRoleMapper.getStaffRole(roleId,staffId);
        if (AssertUtil.isEmpty(staffRole2)){
            StaffRole staffRole1 = new StaffRole();
            staffRole1.setStaffId(staffId);
            staffRole1.setIsDefault(1);
            List<StaffRole> list =staffRoleMapper.selectStaffRoleList(staffRole1);
            if (list.size()>0 && !StringUtils.equals(list.get(0).getRoleId(),roleId)){
                staffRole1.setIsDefault(0);
            }
            staffRole1.setRoleId(roleId);
            staffRoleMapper.insertStaffRole(staffRole1);
        }
    }
    @Override
    public AjaxResult insertAuthStaffAll(String roleId, String staffIds,String platformId) {

        String[] users = Convert.toStrArray(staffIds);
        for (String userId : users)
        {
            StaffRole ur = new StaffRole();
            ur.setStaffId(userId);
            ur.setRoleId(roleId);
//            ur.setPlatformId(platformId);
            AjaxResult ajaxResult = null;
            try {
                //添加用户角色关系
                ajaxResult = addStaffRole(ur);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (StringUtils.equals(ajaxResult.get("code").toString(),"500")){
                return ajaxResult;
            }
        }
        return AjaxResult.success( "添加成功");
    }

    @Override
    public AjaxResult insertAuthStaffAllV2(String roleId, String staffIds, String platformId) {
        String[] users = Convert.toStrArray(staffIds);

        for (String userId : users)
        {
            StaffRole ur = new StaffRole();
            ur.setStaffId(userId);
            ur.setRoleId(roleId);
            staffRoleMapper.insertStaffRole(ur);
        }
        return AjaxResult.success( "添加成功");
    }

    @Override
    @Transactional
    public AjaxResult deleteStaffRoleInfo(StaffRole staffRole) {

        Role role =roleMapper.selectRoleByRoleId(staffRole.getRoleId());
        if (AssertUtil.isEmpty(role)){
            return AjaxResult.error("角色ID不存在！");
        }

        staffRoleMapper.deleteStaffRoleInfo(staffRole);

        return AjaxResult.success( "删除成功");
    }


    @Override
    public StatusResponse delStaffRole(StaffRole staffRole) {
        List<StaffRole>  list = staffRoleMapper.selectStaffRoleList(staffRole);
        if (list.size()>0){
            return  StatusResponse.error(ErrorCode.RECORD_DUPLICATED,"数据已存在！");
        }
        Role role = roleMapper.selectRoleByRoleId(staffRole.getRoleId());
        if (AssertUtil.isEmpty(role)){
            return  StatusResponse.error(ErrorCode.STAFF_NOT_EXIST,"角色不存在！");
        }
//        Platform platform = platformMapper.selectPlatformByPlatformId(staffRole.getPlatformId());
//        if (AssertUtil.isEmpty(platform)){
//            return  StatusResponse.error(ErrorCode.STAFF_NOT_EXIST,"系统id不存在！");
//        }
        staffRoleMapper.deleteAllRole(staffRole.getRoleId());
        role.setDeleted(String.valueOf(1));
        roleMapper.updateRole(role);
        //删除redis角色信息
        redisTemplate.delete(role.getRoleId());

        //更新redis角色信息
        // setRedisRoleMenu(role.getRoleId());
        return StatusResponse.success( "删除成功");
    }

    @Override
    public int deleteStaffRoleInfos(String roleId, String[] staffIds) {
        return  staffRoleMapper.deleteStaffRoleInfos(roleId,staffIds);
    }

    @Override
    public int cancelStaffRole(StaffRole staffRole) {
        return  staffRoleMapper.deleteStaffRoleInfo(staffRole);
    }




    @Override
    public void setRedisRole() {
//        List<Role> list = roleMapper.selectRoleList(new Role());
//        for (int i = 0; i <list.size() ; i++) {
//            setRedisRoleMenu(list.get(i).getRoleId());
//        }
    }

    public void  setRedisRoleMenu(String roleId, String platformId){
        List<Menu>  map = staffMapper.getRoleIdAndPlatformId(roleId, platformId);
        if (AssertUtil.isEmpty(map)){
            map = new ArrayList<>();
        }

        redisTemplate.opsForValue().set( "MENUS_" + platformId + "_" + roleId , map);
    }

    @Override
    public int addAreaRole(String roleId, String areaId) {
        Role role = roleMapper.selectRoleByRoleId(roleId);
        if (AssertUtil.isEmpty(role)){
            throw new BusinessException(ErrorCode.STAFF_HAS_NOT_AREA, "用户不存在");
        }
        role.setRoleId(UuidUtil.getUuid());
        role.setAreaId(areaId);
//        addAreaStaff(roleId,areaId);
        int v =  roleMapper.insertRole(role);

        //更新redis角色信息
//        setRedisRoleMenu(role.getRoleId());

        return v;
    }

    @Override
    @Transactional
    public void setStaffRoleList(String areaId, String staffId, String[] roleIds) {
        if (AssertUtil.isEmpty(staffMapper.selectStaffById(staffId))){
            throw new BusinessException(ErrorCode.STAFF_NOT_EXIST, "用户不存在");
        }
        StaffRole staffRole1 = staffRoleMapper.selectByDefault(staffId);

        staffRoleMapper.deleteAllStaffId(staffId,areaId);
        List<StaffRole> list = new ArrayList<>();

        for (int i = 0; i <roleIds.length ; i++) {
            StaffRole staffRole = new StaffRole();
            staffRole.setRoleId(roleIds[i]);
            staffRole.setStaffId(staffId);
            if (AssertUtil.isEmpty(staffRole1)){
                if (i==0){
                    staffRole.setIsDefault(1);
                }
            }else {
                if (StringUtils.equals(roleIds[i],staffRole1.getRoleId())){
                    staffRole.setIsDefault(1);
                }
            }
            list.add(staffRole);
        }
        staffRoleMapper.batchStaffRole(list);
    }

    public  void  addAreaStaff(String roleId, String areaId){
        StaffRole staffRole = new StaffRole();
        staffRole.setRoleId(roleId);
        List<StaffRole> list =  staffRoleMapper.selectStaffRoleList(staffRole);
        if (list.size()>0){
            for (int i = 0; i <list.size() ; i++) {
                AreaStaff areaStaff = new AreaStaff();
                areaStaff.setAreaId(areaId);
                areaStaff.setStaffId(list.get(i).getStaffId());
                areaStaffService.insertAreaStaff(areaStaff);
            }
        }
    }

    @Override
    public RoleDTO addOrUpdateAreaRole(RedisDetails redisDetails, RoleDTO role) {
        Staff staff = staffMapper.selectStaffById(redisDetails.getStaffId());
        if (AssertUtil.isEmpty(staff) ){
            throw new BusinessException(ErrorCode.STAFF_NOT_EXIST, "用户不存在,无默认园区");
        }
        if (AssertUtil.isEmpty(staff.getAreaId())){
            throw new BusinessException(ErrorCode.STAFF_HAS_NOT_AREA, "用户没有对应园区，无法获取数据");
        }
        if (AssertUtil.isEmpty(role.getId())){
            Role role1 = new Role();
            BeanUtils.copyProperties(role , role1);
            role1.setRoleId(UuidUtil.getUuid());
            role1.setAreaId(staff.getAreaId());
            Role role2 = roleMapper.getAreaByRoleName(role1.getAreaId(),role1.getRoleName());
            if (AssertUtil.isNotEmpty(role2)){
                throw new BusinessException(ErrorCode.STAFF_HAS_NO_ROLE, "角色已存在");
            }
            roleMapper.insertRole(role1);
            //回调id 赋值
            role.setId(role1.getRoleId());
        }else {
            Role role1 =  roleMapper.selectRoleByRoleId(role.getId());
            if (AssertUtil.isEmpty(role1)){
                throw new BusinessException(ErrorCode.STAFF_HAS_NO_ROLE, "该用户没有角色");
            }
            role1.setRoleCode(role.getRoleCode());
            role1.setRoleName(role.getRoleName());
            roleMapper.updateRole(role1);
        }
        //更新redis角色信息
        // setRedisRoleMenu(role.getId());
        return role;
    }

    @Override
    public void removeAreaRole( RoleDTO role) {
        Role role1 =  roleMapper.selectRoleByRoleId(role.getId());
        if (Objects.isNull(role1)){
            throw new BusinessException(ErrorCode.STAFF_HAS_NO_ROLE, "角色不存在");
        }
        role1.setDeleted(String.valueOf(1));
        roleMapper.updateRole(role1);
        //更新redis角色信息
        //setRedisRoleMenu(role1.getRoleId());
    }


    @Override
    public List<Role> getRoleList(String staffId) {
        return roleMapper.getRoleList(staffId);
    }

    @Override
    @Transactional
    public int setDefault(String roleId, String id) {
        Staff staff =  staffMapper.selectStaffById(id);
        Role role = roleMapper.selectRoleByRoleId(roleId);

        List<AreaStaff> list = areaStaffMapper.selectAreaStaffList(new AreaStaff(role.getAreaId(),staff.getId()));
        if (list.size()>0  && AssertUtil.isNotEmpty(role)){
            AreaStaff areaStaff = list.get(0);
            areaStaff.setRoleId(roleId);
            areaStaffMapper.updateAreaStaff(areaStaff);
        }
        return  staffMapper.updateStaff(staff) ;
    }


    @Override
    @Transactional
    public int delRole(String roleId) {
        roleMapper.deleteRoleByRoleId(roleId);
        staffRoleMapper.deleteAllRole(roleId);
        return 0;
    }

    @Override
    public int delAllRole(String roleId) {
        roleMapper.deleteRoleByRoleId(roleId);
        staffRoleMapper.deleteAllRole(roleId);
        areaStaffMapper.deleteRole(roleId);
        return 0;
    }
}
